//
//  LKMyChooseCustomerViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/5/10.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKMyChooseCustomerViewController.h"
#import "LKSearchBar.h"
#import "LKMyChooseCutomerCell.h"
#import "LKCustomerModel.h"
#import "LKContinuInvestViewController.h"
@interface LKMyChooseCustomerViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
@property(nonatomic,strong)LKBaseTableview *tableview;
@property(nonatomic,strong)UIView *topView;
@property(nonatomic,strong)LKSearchBar *searchBar;
@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong) UILabel *namesLabel;
@property(nonatomic,strong)NSMutableArray *dataListArray;
@property(nonatomic,assign)NSInteger currentPageIndex;
@property(nonatomic,assign)NSInteger MaxResultCount;
@property(nonatomic,strong)NSMutableArray *idsArray;
@end

@implementation LKMyChooseCustomerViewController
-(LKBaseTableview *)tableview{
    if (!_tableview) {
        
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH, 46)];
        _topView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_topView];
        //创建searchBar
        LKSearchBar *searchBar = [[LKSearchBar alloc] initWithFrame:CGRectMake(8, 8, WIDTH - 16,30)];
        //默认提示文字
        searchBar.placeholder = @"输入客户编号查询";
        searchBar.delegate = self;
//        searchBar.showsCancelButton = YES;
        [_topView addSubview:searchBar];
        self.searchBar = searchBar;
        self.bottomView.backgroundColor = [UIColor whiteColor];
        _tableview = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 58, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT - 58 - 44) style:UITableViewStyleGrouped registercellClasss:@[@"LKMyChooseCutomerCell"]];
        if (self.isAddContinueHand) {
            [self.bottomView removeFromSuperview];
            _tableview = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 58, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT - 58) style:UITableViewStyleGrouped registercellClasss:@[@"LKMyChooseCutomerCell"]];
        }
        [self.view addSubview:_tableview];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.backgroundColor = cellHeaderBgColor;
        _tableview.emptyDataSetDelegate = self;
        _tableview.emptyDataSetSource = self;
    }
    return _tableview;
}
/**
 头部下拉刷新
 */
-(void)headerReloadData{
    self.currentPageIndex = 1;
    [self getDataListWithSearchname:@""];
}

/**
 尾部上拉加载更多
 */
-(void)footerReloadData{
    
    self.currentPageIndex ++;
    [self getDataListWithSearchname:@""];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableview.estimatedRowHeight = 200;
    self.currentPageIndex = 1;
    self.MaxResultCount = 5;
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerReloadData)];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerReloadData)];
    [self getDataListWithSearchname:@""];
    // Do any additional setup after loading the view.
}
-(void)setNavgationBackBtn{
    [super setNavgationBackBtn];
    
    self.navigationItem.title = @"选择客户";
    if (self.isAddContinueHand) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.titleLabel.font = [UIFont systemFontOfSize:16];
            [btn setTitle:@"保存" forState:UIControlStateNormal];
            [btn setTitleColor:blueDefault forState:UIControlStateNormal];
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
            [btn addTarget:self action:@selector(submitChooseOrder:) forControlEvents:UIControlEventTouchUpInside];
    }

}

-(void)submitChooseOrder:(UIButton *)btn{
    if (self.customersBlcok) {
        self.customersBlcok(self.idsArray);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataListArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LKMyChooseCutomerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMyChooseCutomerCell"];
    cell.customerModel = self.dataListArray[indexPath.section];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 93;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0000000000001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 13;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = cellHeaderBgColor;
    return view;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataListArray.count == 0) {
        return;
    }
    LKCustomerModel *model = self.dataListArray[indexPath.section];
    if (self.isAddContinueHand) {
        if (self.addContinueIdValue) {
            self.addContinueIdValue(model.customerId);
        }
        for (UIViewController *vc in self.navigationController.viewControllers) {
            if ([vc isKindOfClass:[LKContinuInvestViewController class]]) {
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"appointmentProductNotice" object:nil];
                [[NSUserDefaults standardUserDefaults] setObject:model.customerCode forKey:@"fuckContinueOrderKey"];
                [[NSUserDefaults standardUserDefaults] setObject:self.contractCode forKey:@"fuckContinueContractKey"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"sendContinueOrderInfor" object:@{@"CustomerModel":model}];
                
                [self.navigationController popToViewController:vc animated:YES];
                return;

            }
        }
//        [self.navigationController popViewControllerAnimated:YES];
    }
    LKMyChooseCutomerCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.chooseBtn.selected = !cell.chooseBtn.selected;
    if (cell.chooseBtn.selected) {
        [self.idsArray addObject:model];
    }else{
        [self.idsArray removeObject:model];
    }
    NSString *nameStr = @"";
    for (NSInteger i = 0; i < self.idsArray.count; i++) {
        LKCustomerModel *model = self.idsArray[i];
        nameStr = [nameStr stringByAppendingString:[NSString stringWithFormat:@" %@",model.customerName]];
    }
    _namesLabel.text = nameStr;
}
-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"noren_customer"];
}
-(UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT - 43, WIDTH, 43)];
        [self.view addSubview:_bottomView];
        UILabel *nameLabel = [[UILabel alloc] init];
        nameLabel.font = [UIFont systemFontOfSize:15];
        nameLabel.text = @"已选择";
        [_bottomView addSubview:nameLabel];
        [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bottomView.mas_left).offset(16);
            make.centerY.equalTo(_bottomView.mas_centerY);
        }];
        
        UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [sureBtn setTitleColor:blueDefault forState:UIControlStateNormal];
        sureBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        sureBtn.layer.cornerRadius = 4;
        sureBtn.layer.masksToBounds = YES;
        sureBtn.layer.borderWidth = 1;
        sureBtn.layer.borderColor = blueDefault.CGColor;
        [_bottomView addSubview:sureBtn];
        [sureBtn addTarget:self action:@selector(submitChooseOrder:) forControlEvents:UIControlEventTouchUpInside];
        [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_bottomView.mas_right).offset(-16);
            make.centerY.equalTo(_bottomView.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(55, 25));
        }];
        _namesLabel = [[UILabel alloc] init];
        _namesLabel.textColor = blueDefault;
        _namesLabel.textAlignment = NSTextAlignmentLeft;
        _namesLabel.font = [UIFont systemFontOfSize:15];
        [_bottomView addSubview:_namesLabel];
        [_namesLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(sureBtn.mas_left).offset(-6);
            make.left.equalTo(nameLabel.mas_right).offset(6);
            make.centerY.equalTo(_bottomView.mas_centerY);

        }];
        
    }
    return _bottomView;
}
/**
 获取数据列表
 */
-(void)getDataListWithSearchname:(NSString *)customerName{
    NSString *PageIndexStr = [NSString stringWithFormat:@"%ld",self.currentPageIndex];
    NSString *MaxResultCountStr = [NSString stringWithFormat:@"%ld",self.MaxResultCount];
    NSDictionary *param = @{@"PageIndex":PageIndexStr,@"MaxResultCount":MaxResultCountStr,@"SearchCustomerNameOrIDCard":customerName};
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:getChooseCustomerListUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        if (self.currentPageIndex == 1) {
            [self.dataListArray removeAllObjects];
        }
        NSArray *dataArra = responseObject[@"result"][@"items"];
        NSString *count = responseObject[@"result"][@"totalCount"];
        for (NSDictionary *dic in dataArra) {
            LKCustomerModel *model = [LKCustomerModel modelWithDictionary:dic];
            [self.dataListArray addObject:model];
        }
        
        if ([count integerValue] == self.dataListArray.count) {
            [self.tableview.mj_footer endRefreshingWithNoMoreData];
        }
        if (self.dataListArray.count == 0) {
            self.tableview.mj_footer.hidden = YES;
        }
        [self.tableview reloadData];
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
-(NSMutableArray *)dataListArray{
    if (!_dataListArray) {
        _dataListArray = [[NSMutableArray alloc] init];
    }
    return _dataListArray;
}
-(NSMutableArray *)idsArray{
    if (!_idsArray) {
        _idsArray = [[NSMutableArray alloc] init];
    }
    return _idsArray;
}
#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
        searchBar.showsCancelButton = YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"SearchButton");
    self.currentPageIndex = 1;
    [self.idsArray removeAllObjects];
    [self.dataListArray removeAllObjects];
    [self getDataListWithSearchname:searchBar.text];
    [searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
    searchBar.text = @"";
    self.currentPageIndex = 1;
    [self.idsArray removeAllObjects];
    [self.dataListArray removeAllObjects];
    [self getDataListWithSearchname:searchBar.text];
    [searchBar resignFirstResponder];
    //    [searchBar setShowsCancelButton:NO animated:YES];
    //    [self.searchBar resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
